package com.ugoodtech.mdcc.client.controller;


import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.dto.GroupResponse;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.service.QuestionService;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.repository.AuditColorReportRepository;
import com.ugoodtech.mdcc.core.repository.AuditReportRepository;
import com.ugoodtech.mdcc.core.repository.NationRepository;
import com.ugoodtech.mdcc.core.repository.QuestionAnswerOptionRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.Na;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(description = "question审核接口")
@RestController
@RequestMapping("/questionAudit")
public class QuestionAuditController {

    private static Logger logger = LoggerFactory.getLogger(QuestionAuditController.class);

    private List<AuditColorReport> colorReports = null;

    @Autowired
    private AuditReportRepository auditReportRepository;

    @Autowired
    private AuditColorReportRepository auditColorReportRepository;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private NationRepository nationRepository;

    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;


    @ApiOperation("获取章节分组和题目")
    @RequestMapping(value = "/getGroups", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getGroups(
            Principal principal,
            @ApiParam("章节id") @RequestParam("sectionId") Long sectionId,
            @ApiParam("题目拥有者") @RequestParam("owner") Integer owner,
            @ApiParam("报告id") @RequestParam("reportId") Long reportId
    ) {
//        if (principal == null) {
//            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
//        }
        logger.info("开始调用此方法");
        Long time = System.currentTimeMillis();
        if (reportId != null && reportId != 0) {
            colorReports = auditColorReportRepository.selectAnswer(reportId);
        }
        List<QuestionGroup> questionGroups = questionService.getQuestions(sectionId,owner);
        AuditReport auditReport = auditReportRepository.findOne(reportId);
        if (auditReport == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此报告");
        }

        List<Object> data = new ArrayList<>();
        for (QuestionGroup questionGroup : questionGroups) {
            data.add(GroupResponse.turnGroupToResponse(questionGroup));
            List<Question> questionGroupList = questionService.getQuestionsByGroup(questionGroup.getId(),owner);
            for (Question question : questionGroupList) {
                if (null != owner && question.getOwner() != owner && question.getOwner()!=2){
                    continue;
                }
                Long question_id = Long.valueOf(question.getId());
                if (question_id == 146 || question_id == 147 || question_id == 148 || question_id == 149 || question_id == 150 || question_id == 151 ||
                        question_id == 152 || question_id == 153 || question_id == 154) {
                    continue;
                }
                if (reportId != null && reportId != 0) {
                    question = selectAnswer(question, reportId);
                }

                List<QuestionAnswerOption> questionAnswerOptions = questionService.getOptionsByGroup(question.getId(),owner);
                question.setOptions(questionAnswerOptions);
                List<Question> questions = new ArrayList<>();
                questions.add(question);
                if (QuestionCategory.TEXT.equals(question.getCategory())) {
                    Map<String, Object> textQuestion = new HashMap<>();
                    textQuestion.put("category", question.getCategory().name());
                    textQuestion.put("required", Boolean.valueOf(question.getRequired()));
                    textQuestion.put("type", "question");
                    textQuestion.put("inputList", questions);
                    data.add(textQuestion);
                } else {
                    data.add(question);
                }
            }
        }

        QuestionController.In excel = new QuestionController().new In();
        if (sectionId == 10) {
            excel.setExcel(true);
            data.add(excel);
        } else {
            data.add(excel);
        }
        colorReports = null;
        logger.info("调用完毕");
        logger.info("总耗时：" + (System.currentTimeMillis() - time));
        return JsonResponse.successResponseWithData(data);
    }

    private Question selectAnswer(Question question, Long report_id) {
        if (colorReports != null) {
            for (AuditColorReport report : colorReports) {
                if (question.getId().equals(report.getQuestionId())) {
                    if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                        question.setAnswer_other(report.getAnswerOther());
                    } else {
                        question.setAnswer_other("");
                    }
                    if (report.getQuestionId() == 173) {
                        if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                            Nation nation = nationRepository.selectByProvince(report.getAnswerOther());
                            if (nation == null) {
                                question.setAnswer_other("");
                            } else {
                                question.setAnswer_other(nation.getProvince());
                            }
                        }
                    }
                    if (report.getQuestionId() == 174) {
                        if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                            List<Nation> nationList = nationRepository.selectByCity(report.getAnswerOther());
                            Nation nation = CollectionUtils.isEmpty(nationList) ? null : nationList.get(0);
                            if (nation == null) {
                                question.setAnswer_other("");
                            } else {
                                question.setAnswer_other(nation.getCity());
                            }
                        }
                    }
                    if (report.getQuestionId() == 8L) {
                        StringBuffer stringBuffer = new StringBuffer("");
                        if (StringUtils.isNotEmpty(report.getAnswerId())) {
                            String[] ids = report.getAnswerId().split(",");
                            for (String id : ids) {
                                if (StringUtils.isNotEmpty(id)) {
                                    QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                                    if (answerOption != null && StringUtils.isNotEmpty(answerOption.getName())) {
                                        stringBuffer.append(answerOption.getName() + ",");
                                    }
                                }
                            }
                        }
                        if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                            question.setAnswer_other2(report.getAnswerOther());
                        }
                        question.setAnswer_other(stringBuffer.toString());
                    }

                    if (StringUtils.isNotEmpty(report.getAnswerPhoto())) {
                        question.setAnswer_photo(report.getAnswerPhoto());
                    } else {
                        question.setAnswer_photo("");
                    }
                    if (report.getAnswerId() != null && report.getAnswerId().indexOf(",") != -1) {
                        question.setSelected(report.getAnswerId());
                    } else if (StringUtils.isNotEmpty(report.getAnswerId()) && Long.valueOf(report.getAnswerId()) != 0) {
                        question.setSelected(report.getAnswerId());
                    } else {
                        question.setSelected("");
                    }
                }
            }
            return question;
        }

        return question;
    }
}
